package com.nexgo.payment.action.scan;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.nexgo.oaf.apiv3.SdkResult;
import com.nexgo.oaf.apiv3.device.scanner.OnScannerListener;
import com.nexgo.oaf.apiv3.device.scanner.Scanner;
import com.nexgo.oaf.apiv3.device.scanner.ScannerCfgEntity;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.api.ApiDeviceEngine;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 扫码输入
 *
 * Created by wanghongyang on 2017/9/1.
 */
public class BccScanPresenter implements BccScanContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(BccScanPresenter.class.getSimpleName());

    private final BccScanContract.View mView;
    private DataSource mRepository;
    private final Handler mHandler;
    private Scanner mScanner;
    private final TransData mTransData;
    private boolean isFirstTimes = true;
    private OnActionListener mListener;
    private boolean mIsScanNext = false;
    private HashMap< String , String > result = null;

    public BccScanPresenter(@NonNull BccScanContract.View view, @NonNull DataSource dataSource, @NonNull TransData transData) {
        this.mView = checkNotNull(view);
        this.mRepository = checkNotNull(dataSource);
        mTransData = checkNotNull(transData);
        view.setPresenter(this);
        mHandler = new Handler(Looper.getMainLooper());
        mScanner = ApiDeviceEngine.getInstance().getScanner(App.sContext);
    }


    @Override
    public void start() {
        postMainThread(() -> mView.showScanCode());

        if(isFirstTimes) {
            postMainThread(() -> mView.showAmount(mTransData.getAmount()));
            postMainThread(() -> mView.showCountTime(SysConstant.TIME_OUT_60));
            isFirstTimes = false;
        }
    }

    @Override
    public void pause() {}

    @Override
    public void destroy() {
       /* if (mScanner != null) {
            mScanner.stopScan();
        }*/
    }

    /*
    *
    *
    *  看扫到的条码规则
    * */
    @Override
    public HashMap<String, String> checkCodeData(String codeData) {
        HashMap<String, String> spKeyMap = new HashMap<>();
        String str ;
        int i = Integer.parseInt(codeData.substring(0,2));
        if( i >= 13 && i <= 17){  //微信
            str = "01";
        }else if( i >= 20 && i <= 29){  // 支付宝
            str = "02";
        }else if( i == 10 || i == 62){  //银联
            str = "03";
        }else{
            return null;
        }
        spKeyMap.put ("code",codeData);
        spKeyMap.put ("channel",str);
        return spKeyMap;
    }

    @Override
    public void onStartScanner() {
        try {
            ScannerCfgEntity cfgEntity = new ScannerCfgEntity();
            cfgEntity.setAutoFocus(true);
            cfgEntity.setBulkMode(false);
            cfgEntity.setUsedFrontCcd(false);
            mScanner.initScanner(cfgEntity, mInitScannerListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStopScanner() {
        if (mScanner != null) {
            mScanner.stopScan();
        }
    }

    @Override
    public void onErrCode(int retCode) {
        switch (retCode) {
            case SdkResult.TimeOut:
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_time_out)));
                break;
            case SdkResult.Scanner_Customer_Exit:
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_cancel)));
                break;
            default:
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_fail)));
                break;
        }
    }

    /**
     * 初始化扫码回调
     */
    private OnScannerListener mInitScannerListener = new OnScannerListener() {
        @Override
        public void onInitResult(int retCode) {
            mLog.debug("初始化扫码，返回状态：{}",retCode);
            if (retCode != SdkResult.Success){
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_init_error)));
                return;
            }
            int result = mScanner.startScan(SysConstant.TIME_OUT_60, mStartScannerListener);
            mLog.debug("启动扫码，返回状态：{}",result);
            if (result != SdkResult.Success){
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_start_error)));
            }
        }

        @Override
        public void onScannerResult(int retCode, String data) {}
    };

    /**
     * 扫码结果回调
     */
    private OnScannerListener mStartScannerListener = new OnScannerListener() {

        @Override
        public void onInitResult(int retCode) {}

        @Override
        public void onScannerResult(int retCode, String data) {
            mLog.debug("扫码结果，返回状态：{}",retCode);
            if (retCode != SdkResult.Success){
                onErrCode(retCode);
                return;
            }
            mLog.debug("扫码返回数据：{}",data);
//            HashMap< String , String > result = checkCodeData(data);
             result = checkCodeData(data);
            if(result == null){
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_code_error)));
                return ;
            }
            mIsScanNext = true; //记录扫码后的状态
//            postMainThread(() -> mView.showScanSuccessful(result));
        }
    };

    @Override
    public void showOnScanNextAndRestart() {
        if (!mIsScanNext) return;
        postMainThread(() -> mView.showScanSuccessful(result));
        mIsScanNext = false;
    }

    @Override
    public void importScanCode(String code) {
        mLog.debug("手输条码返回数据：{}",code);
        result = checkCodeData(code);
        if(result == null){
            postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_code_error)));
            return ;
        }
        postMainThread(() -> mView.showScanSuccessful(result));
    }


    private void postMainThread(Runnable runnable) {
        if (mView.isActive()) {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                runnable.run();
            } else {
                mHandler.post(runnable);
            }
        }
    }
}
